/*
 * Copyright (c) 2011 Samuel Ventura All Rights Reserved
 */
package dev2net;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import opto22.snappac.comm.DefaultIoUnit;
import opto22.snappac.comm.IoUnit;
import opto22.snappac.comm.PointInfo;

/**
 *
 * @author samuel
 */
public class MmuConfig {

    private List<MmpConfig> mmpConfigs = Collections.synchronizedList(new LinkedList());
    private IoUnit ioUnit;
    
    MmuConfig(String ip, int port) {
        ioUnit = DefaultIoUnit.newInstance(ip, port, 200, 1000);
    }

    public int getPointCount() {
        return mmpConfigs.size();
    }
        
    void add(MmpConfig mmpc) {
        mmpc.setMmuConfig(this);
        mmpConfigs.add(mmpc);
    }

    void remove(MmpConfig mmpc) {
        mmpConfigs.remove(mmpc);
    }

    void sync() throws IOException {
        //TODO is this copy access enough?
        List<MmpConfig> list = new ArrayList(mmpConfigs);
        for(MmpConfig mmpc : list) {
            try {
                syncPoint(mmpc);
            } catch (IOException ex) {
                Util.out(ex.getMessage());
                throw ex;
            }
        }
    }

    private void syncPoint(MmpConfig mmpc) throws IOException {
        PointInfo pi = mmpc.getPointInfo();
        if (pi == null) {
            pi = ioUnit.getPointInfo(mmpc.getModuleIndex(), mmpc.getPointIndex());
            mmpc.setPointInfo(pi);
        }
        if (pi.isAnalog()) {
            mmpc.setRead(ioUnit.getAnalogPointValue(mmpc.getModuleIndex(), mmpc.getPointIndex()));
        } else {
            mmpc.setRead(ioUnit.getDigitalPointState(mmpc.getModuleIndex(), mmpc.getPointIndex())?1:0);
        }
        Float w = mmpc.getWrite();
        if (pi.isWritable() && w != null) {
            if (pi.isAnalog()) {
                ioUnit.setAnalogPointValue(mmpc.getModuleIndex(), mmpc.getPointIndex(), w);
            } else {
                ioUnit.setDigitalPointState(mmpc.getModuleIndex(), mmpc.getPointIndex(), w!=0);
            }        
            mmpc.clearWrite();
        }
    }
}
